<?php
date_default_timezone_set('Asia/Shanghai');
/**
 * 获取后台管理设置的网站信息，此类信息一般用于前台，推荐使用sp_get_site_options
 */
function get_site_options(){
	$web_info = F("web_info");
	if(empty($web_info)){
		$options_obj = M("Options");
		$option = $options_obj->where("option_name='web_info'")->find();

		if($option){
			$web_info = json_decode($option['option_value'],true);
		}else{
			$web_info = array();
		}
		F("web_info", $web_info);
	}
	//$site_options['site_tongji']=htmlspecialchars_decode($site_options['site_tongji']);
	return $web_info;	
}

function get_client_ip2(){
    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'),'unknown')) {

        $ip = getenv('HTTP_CLIENT_IP');

    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),'unknown')) {

        $ip = getenv('HTTP_X_FORWARDED_FOR');

    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'),'unknown')) {

        $ip = getenv('REMOTE_ADDR');

    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {

        $ip = $_SERVER['REMOTE_ADDR'];

    }

    return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}

/**
 * 获取支付宝配置
 */
function get_alipay_options(){
	$ali_pay = F("ali_pay");
	if(empty($ali_pay)){
		$options_obj = M("Options");
		$option = $options_obj->where("option_name='ali_pay'")->find();

		if($option){
			$ali_pay = json_decode($option['option_value'],true);
		}else{
			$ali_pay = array();
		}
		F("ali_pay", $ali_pay);
	}
	return $ali_pay;	
}

/**
 * 获取微信配置
 */
function get_wchat_options(){
	$wx_pay = F("wx_pay");
	if(empty($wx_pay)){
		$options_obj = M("Options");
		$option = $options_obj->where("option_name='wx_pay'")->find();

		if($option){
			$wx_pay = json_decode($option['option_value'],true);
		}else{
			$wx_pay = array();
		}
		F("wx_pay", $wx_pay);
	}
	return $wx_pay;	
}

/**
	 * @param   $type 生成缩略图的方式
	*IMAGE_THUMB_SCALE     =   1 ; //等比例缩放类型
	*IMAGE_THUMB_FILLED    =   2 ; //缩放后填充类型
	*IMAGE_THUMB_CENTER    =   3 ; //居中裁剪类型
	*IMAGE_THUMB_NORTHWEST =   4 ; //左上角裁剪类型
	*IMAGE_THUMB_SOUTHEAST =   5 ; //右下角裁剪类型
	*IMAGE_THUMB_FIXED     =   6 ; //固定尺寸缩放类型

	**/
function getPicThumb($ImagePath,$width,$height,$type,$savePath){
		$image = new \Think\Image(); 
		$image->open($ImagePath);
		// 按照设定的生成方式产生缩略图
		$image->thumb($width,$height,$type)->save($savePath);
}

/**
 * 获取前台模板根目录
 */
function sp_get_theme_path(){
	// 获取当前主题名称
	$tmpl_path=C("SP_TMPL_PATH");
	$theme      =    C('SP_DEFAULT_THEME');
	if(C('TMPL_DETECT_THEME')) {// 自动侦测模板主题
		if(cookie('think_template')){
			$theme = cookie('think_template');
		}
		if(!file_exists($tmpl_path."/".$theme)){
			$theme  =   C('SP_DEFAULT_THEME');
		}
		cookie('think_template',$theme,864000);
	}

	return __ROOT__.'/'.$tmpl_path.$theme."/";
}

/**
 * 给没有后缀的模板文件，添加后缀名
 * @param string $filename_nosuffix
 */
function sp_add_template_file_suffix($filename_nosuffix){
    
    if(file_exists_case($filename_nosuffix.C('TMPL_TEMPLATE_SUFFIX'))){
        $filename_nosuffix = $filename_nosuffix.C('TMPL_TEMPLATE_SUFFIX');
    }else if(file_exists_case($filename_nosuffix.".php")){
        $filename_nosuffix = $filename_nosuffix.".php";
    }else{
        $filename_nosuffix = $filename_nosuffix.C('TMPL_TEMPLATE_SUFFIX');
    }

    return $filename_nosuffix;
}
//获取导航
function sp_get_menu_tree($id="main"){
	$navs=F("site_nav_".$id);
	if(empty($navs)){
		$navs=_sp_get_menu_datas($id);
	}

	import("Think.Tree");
	$tree = new \Tree();
	$tree->init($navs);
	return $tree->get_tree_array(0, "");
}

//获取店铺导航
function sp_get_store_menu_tree($id){

    $navs=_sp_get_store_menu_datas($id);
	import("Think.Tree");
	$tree = new \Tree();
	$tree->init($navs);
	return $tree->get_tree_array(0, "");
}
//获取店铺导航
function _sp_get_store_menu_datas($id){
	$nav_obj= M("store_type");
	$oldid=$id;
	$id= intval($id);
	if(empty($id)){
		return array();
	}

	$navs= $nav_obj->where(array('shore_id'=>$id,'status'=>1))->order(array("listorder" => "ASC"))->select();
	F("site_store_nav_".$oldid,$navs);
	return $navs;
}
function _sp_get_menu_datas($id){
	$nav_obj= M("Nav");
	$oldid=$id;
	$id= intval($id);
	$id = empty($id)?"main":$id;
	if($id=="main"){
		$navcat_obj= M("NavCat");
		$main=$navcat_obj->where("active=1")->find();
		$id=$main['navcid'];
	}

	if(empty($id)){
		return array();
	}

	$navs= $nav_obj->where(array('cid'=>$id,'status'=>1))->order(array("listorder" => "ASC"))->select();
	
	$default_app=strtolower(C("DEFAULT_MODULE"));
	$g=C("VAR_MODULE");
	foreach ($navs as $key=>$nav){
		$href=htmlspecialchars_decode($nav['href']);
		$hrefold=$href;
		if($hrefold=="home"){
			$href=__ROOT__."/";
		}else{
			$href=$hrefold;
		}
		
		$nav['href']=$href;
		$navs[$key]=$nav;
	}
	F("site_nav_".$oldid,$navs);
	return $navs;
}


/**
 * 根据幻灯片ID获取所有幻灯片
 * @param string $slide 幻灯片ID
 * @return array;
 */
function sp_getslide($id){
    $slide_obj= M("group_ad");
    $slides=$slide_obj->where("ad_status=1 and id=".$id)->find();
    $ads=json_decode($slides['ad_data'],TRUE);
    $ads=$ads['AdItem'];
	return $ads;
}


//加密函数
function passport_encrypt($txt, $key) {
	srand((double)microtime() * 1000000);
	$encrypt_key = md5(rand(0, 32000));
	$ctr = 0;
	$tmp = '';
	for($i = 0;$i < strlen($txt); $i++) {
	   $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
	   $tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
	}
	return base64_encode(passport_key($tmp, $key));
}
//解密函数
function passport_decrypt($txt, $key) {
	$txt = passport_key(base64_decode($txt), $key);
	$tmp = '';
	for($i = 0;$i < strlen($txt); $i++) {
	   $md5 = $txt[$i];
	   $tmp .= $txt[++$i] ^ $md5;
	}
	return $tmp;
}

function passport_key($txt, $encrypt_key) {
	$encrypt_key = md5($encrypt_key);
	$ctr = 0;
	$tmp = '';
	for($i = 0; $i < strlen($txt); $i++) {
	   $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
	   $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
	}
	return $tmp;
}

function getAreaList(){
	$sys_area=M('sys_area');
    $list = $sys_area->order('sort asc')->select();
    return $list;
}

function getProvinceList($area_id = 0){
    	$sys_province=M('sys_province');
        if ($area_id == - 1) {
            $list = array();
        } elseif ($area_id == 0||$area_id == -10) {
            $list = $sys_province->order('sort asc')->select();
        } else {
        	$list = $sys_province->where( 'area_id='.$area_id)->order('sort asc')->select();
        }
        if($area_id==-10){
        	return json_encode($list);
        }else{
        	return $list;
        }
       
}
function getProvinceInfo($Province_id){
	$sys_province=M('sys_province');
	$info = $sys_province->find($Province_id);
	return $info;
}
function getCityList($province_id = 0){
    	$sys_city=M('sys_city');
       
        if ($province_id == 0||$province_id == -10) {
            $list = $sys_city->order('sort asc')->select();
        } else {
        	$list = $sys_city->where( 'province_id='.$province_id)->order('sort asc')->select();
        }
        if($province_id==-10){
        	return json_encode($list);
        }else{
        	return $list;
        }
       
       
}
function getCityInfo($city_id){
	$sys_city=M('sys_city');
	$info = $sys_city->find($city_id);
	return $info;
}

function getDistrictList($city_id = 0){
    	$sys_district=M('sys_district');
    	
        if ($city_id == 0||$city_id == -10) {
            $list = $sys_district->order('sort asc')->select();
        } else {
        	$list = $sys_district->where( 'city_id='.$city_id)->order('sort asc')->select();
        }
      	
        
        if($city_id=='-10'){
        	return json_encode($list);
        }else{
        	return $list;
        }
        
      
    }
function getDistrictInfo($district_id){
	$sys_district=M('sys_district');
	$info = $sys_district->find($district_id);
	return $info;
}


function getCity_array(){
	$sys_district=M('sys_district');
	$list = $sys_district->field('district_id,city_id')->order('sort asc')->select();
	$newlist=array();
	foreach($list as $key=>$v){
		$newlist[$v['district_id']]=$v['city_id'];
	}
	return $newlist;
}

function get_freight($shop_id,$city_id,$num){
	$shop=M('shop');
	$transport_extend=M('transport_extend');
	$shop_info=$shop->field('transport_id,goods_freight')->find($shop_id);
	
	if($shop_info['transport_id']!=0&&$shop_info['transport_id']!=null){
		$map['transport_id']=$shop_info['transport_id'];
		$map['_string']='FIND_IN_SET('.$city_id.',area_id)';
		$transport=$transport_extend->where($map)->find(true);
		
		if($transport){
			//首重
			$s_price=$transport['sprice'];
			//续重
			$x_price=(($num-$transport['snum'])/$transport['xnum'])*$transport['xprice'];
			$freight=$s_price+$x_price;
		}else{
			$map2['transport_id']=$shop_info['transport_id'];
			$map2['is_default']=1;
			$transport=$transport_extend->where($map)->find();
			//首重
			$s_price=$transport['sprice'];
			//续重
			$x_price=(($num-$transport['snum'])/$transport['xnum'])*$transport['xprice'];
			$freight=$s_price+$x_price;
			
		}
	}else{
		$freight=$shop_info['goods_freight'];
	}
	return $freight;
}
	//获取提现状态
	function get_withdrawal($log_id){
		$users_getmoney=M('users_getmoney');
		$rs=$users_getmoney->where('log_id='.$log_id)->find();
		if($rs){
			if($rs['status']==0){
				return '&nbsp;(申请中)';
			}
			if($rs['status']==1){
				return '&nbsp;(已同意,等待转账) ';
			}
			if($rs['status']==2){
				return '&nbsp;(拒绝,钱已退余额)';
			}
			if($rs['status']==3){
				return '&nbsp;(打款成功)';
			}
		}else{
			return '';
		}
	}
	//获取用户信息
	function get_user($user_id){
		$users=M('users');
		$users_info=$users->find($user_id);
		return $users_info;
	}
	
	//获取本地店铺
	function get_local_store(){
		$city_id=cookie('site_city_id');
		$store_arr=M('store')
				->join('yt_sys_district on yt_sys_district.district_id=yt_store.district','left')
				->join('yt_sys_city on yt_sys_city.city_id=yt_store.city','left')
				->join('yt_store_template on yt_store_template.store_id=yt_store.id','left')
				->field('yt_store.store_desccredit,yt_store.store_deliverycredit,yt_store.store_servicecredit,yt_store.id,yt_store.quanwang,yt_store.district,yt_store.title,yt_store_template.portrait,yt_store_template.logo,yt_sys_district.district_name,yt_sys_city.city_name ')
				->where('yt_store.status=1 and (yt_store.city='.$city_id.' or yt_store.quanwang=1)')
				->order('yt_store.id desc')
				->limit('5')
				->select();
		return $store_arr;
	}
	
	function post_url($url, $params){
        $ch = curl_init();
        if (stripos($url, "https://") !== false) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        $content = curl_exec($ch);
        $status = curl_getinfo($ch);
        curl_close($ch);
        if (intval($status["http_code"]) == 200) {
            return $content;
        } else {
            return false;
        }
    }
	function duanxin($code,$mobile){
		$data['username']=C('duanxin.username');
		$data['password']=C('duanxin.password');
		$data['mobile']=$mobile;
		$data['content']='【58代言】'.$code.'(动态验证),请在5分钟内填写';
		$url=C('duanxin.url');
		$rs=post_url($url,$data);
	 
		$xml = simplexml_load_string($rs);
		$rs = json_decode(json_encode($xml),TRUE);
		return $rs;
	}
	
		//获取优惠券金额
	function get_coupon_price($user_id,$coupon_id){
		$coupon_type=M('coupon_type');
		$coupon=M('coupon');
		$result=$coupon->where("coupon_type_id=$coupon_id and uid=$user_id and state=1")->select();
		if($result){
			$rs=$coupon_type->find($coupon_id);
		}else{
			$rs['money']=0;
		}
		return $rs['money'];
	}
	
	/**
     * 返回今日开始和结束的时间戳
     *
     * @return array
     */
    function today()
    {
        return [
            mktime(0, 0, 0, date('m'), date('d'), date('Y')),
            mktime(23, 59, 59, date('m'), date('d'), date('Y'))
        ];
    }

    /**
     * 返回昨日开始和结束的时间戳
     *
     * @return array
     */
    function yesterday()
    {
        $yesterday = date('d') - 1;
        return [
            mktime(0, 0, 0, date('m'), $yesterday, date('Y')),
            mktime(23, 59, 59, date('m'), $yesterday, date('Y'))
        ];
    }

    /**
     * 返回本周开始和结束的时间戳
     *
     * @return array
     */
    function week()
    {
        $timestamp = time();
        return [
            strtotime(date('Y-m-d', strtotime("+0 week Monday", $timestamp))),
            strtotime(date('Y-m-d', strtotime("+0 week Sunday", $timestamp))) + 24 * 3600 - 1
        ];
    }

    /**
     * 返回上周开始和结束的时间戳
     *
     * @return array
     */
    function lastWeek()
    {
        $timestamp = time();
        return [
            strtotime(date('Y-m-d', strtotime("last week Monday", $timestamp))),
            strtotime(date('Y-m-d', strtotime("last week Sunday", $timestamp))) + 24 * 3600 - 1
        ];
    }

    /**
     * 返回本月开始和结束的时间戳
     *
     * @return array
     */
    function month($everyDay = false)
    {
        return [
            mktime(0, 0, 0, date('m'), 1, date('Y')),
            mktime(23, 59, 59, date('m'), date('t'), date('Y'))
        ];
    }

    /**
     * 返回上个月开始和结束的时间戳
     *
     * @return array
     */
    function lastMonth()
    {
        $begin = mktime(0, 0, 0, date('m') - 1, 1, date('Y'));
        $end = mktime(23, 59, 59, date('m') - 1, date('t', $begin), date('Y'));

        return [$begin, $end];
    }

    /**
     * 返回今年开始和结束的时间戳
     *
     * @return array
     */
    function year()
    {
        return [
            mktime(0, 0, 0, 1, 1, date('Y')),
            mktime(23, 59, 59, 12, 31, date('Y'))
        ];
    }

    /**
     * 返回去年开始和结束的时间戳
     *
     * @return array
     */
    function lastYear()
    {
        $year = date('Y') - 1;
        return [
            mktime(0, 0, 0, 1, 1, $year),
            mktime(23, 59, 59, 12, 31, $year)
        ];
    }

    function dayOf()
    {

    }

    /**
     * 获取几天前零点到现在/昨日结束的时间戳
     *
     * @param int $day 天数
     * @param bool $now 返回现在或者昨天结束时间戳
     * @return array
     */
    function dayToNow($day = 1, $now = true)
    {
        $end = time();
        if (!$now) {
            list($foo, $end) = yesterday();
        }

        return [
            mktime(0, 0, 0, date('m'), date('d') - $day, date('Y')),
            $end
        ];
    }

    /**
     * 返回几天前的时间戳
     *
     * @param int $day
     * @return int
     */
    function daysAgo($day = 1)
    {
        $nowTime = time();
        return $nowTime - self::daysToSecond($day);
    }

    /**
     * 返回几天后的时间戳
     *
     * @param int $day
     * @return int
     */
    function daysAfter($day = 1)
    {
        $nowTime = time();
        return $nowTime + self::daysToSecond($day);
    }

    /**
     * 天数转换成秒数
     *
     * @param int $day
     * @return int
     */
    function daysToSecond($day = 1)
    {
        return $day * 86400;
    }

    /**
     * 周数转换成秒数
     *
     * @param int $week
     * @return int
     */
    function weekToSecond($week = 1)
    {
        return self::daysToSecond() * 7 * $week;
    }

   function startTimeToEndTime()
    {

    }
	function wunen_register($phone,$password){
		$oCurl = curl_init();
		$url='http://58wu.net/Handler/LoginHandler.ashx?username='.$phone.'&password='.$password;
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        //增加代理
        //curl_setopt($oCurl, CURLOPT_PROXY, HTTP_PROXY_IP_PORT);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
	}
	
	function sp_getad($ad){
		$ad_obj= M("ad");
		$ad=$ad_obj->field("ad_content")->where("ad_name='$ad' and status=1")->find();
		return htmlspecialchars_decode($ad['ad_content']);
	}
	function log_result($file,$word) 
    {
        $fp = fopen($file,"a");
        flock($fp, LOCK_EX) ;
        fwrite($fp,"执行日期：".strftime("%Y-%m-%d-%H：%M：%S",time())."\n".$word."\n\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }
	function is_weixin() { 
   		if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        	return true;
  	    }else{
  	    	return false;
  	    }

    }
	
	function get_daiyan_list(){
		$rs=M('order_goods')
			->field('yt_order_goods.goods_name,yt_order_goods.recommend_price,yt_users.username,yt_order_goods.goods_id,yt_order_goods.recommend_id')
			->join('yt_users ON yt_order_goods.recommend_id = yt_users.id','left')
			->where('yt_order_goods.lock_state=1 and yt_order_goods.recommend_id<>"" and yt_order_goods.recommend_price>0 ')
			->order('yt_order_goods.rec_id desc')
			->select();
		return $rs; 
	}
	function get_userdaiyan_list($uid){
		$rs=M('order_goods')
			->field('yt_order_goods.goods_name,yt_order_goods.recommend_price,yt_users.username,yt_order_goods.goods_id,yt_order_goods.recommend_id')
			->join('yt_users ON yt_order_goods.recommend_id = yt_users.id','left')
			->where('yt_order_goods.lock_state=1 and yt_order_goods.recommend_id='.$uid)
			->select();
		return $rs; 
	}
	function get_page($id){
		$article_posts=M('article_posts');
    	$page=$article_posts->find($id);
    	return $page;
	}
	
	/*
	* 跳转到指定页面获取微信access_token代码
	* @param string $appid：微信公众号的appid(具有网页授权接口)
	* @param string $redirecturl：指定跳转的获取access_token的url
	* @param string $scope：snsapi_userinfo为获取用户基本信息，snsapi_base为获取用户openid
	*/
	
	function get_access_token($appid,$redirecturl,$scope='snsapi_login'){
		$redirecturl=urlencode($redirecturl);
  		$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirecturl.'&response_type=code&scope=snsapi_userinfo&state=state#wechat_redirect'; 
       	// $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirecturl.'&response_type=code&scope='.$scope.'&state=123#wechat_redirect';
		header("location:".$url);
		exit;
	}
	
	/*
	* 通过网页授权获取微信用户基本信息
	* @param string $appid：微信公众号的appid(具有网页授权接口)
	* @param string $appsecret：微信公众号的$appsecret
	* @param string $code：get_access_token方法返回的代码
	*/
	
	function get_weixin_info($appid,$appsecret,$code){
		$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
		$rs = file_get_contents($url);
		$rs = json_decode($rs,TRUE);
		return $rs;
	}
	
	function get_weixin_user_info($token,$openid){
		$abs_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$token."&openid=".$openid."&lang=zh_CN";  
		$abs_url_data = file_get_contents($abs_url);  
		$obj_data=json_decode($abs_url_data,true);
		return $obj_data;	
	}
	/*订单支付成功通知
	* @param string $openid：用户OPPENDID
	* @param string $url：订单URL
	* @param string $keyword1：订单号
	* @param string $keyword2：支付时间
	* @param string $keyword3：支付金额
	* @param string $keyword4：支付方式
	*/
	function send_info($openid,$url,$keyword1,$keyword2,$keyword3,$keyword4){
		$appid=C('weixin.APP_KEY');
    	$appsecret=C('weixin.APP_SECRET');
		$data = json_decode(file_get_contents("access_token.json"),true);//建立一个文件把第一次请求到的token对象放进去
		
		if (empty($data) || $data['expire_time']< time()) {
			$json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret);
			$access_token=json_decode($json_token,true);
			//获得access_token
			$token=$access_token[access_token];
			if($token) {
				 $data['expire_time'] = time()+($access_token['expires_in'] - 100);
				 $data['access_token'] = $token;
				 $fp = fopen("access_token.json", "w");
				 fwrite($fp, json_encode($data));
				 fclose($fp);
			}
		}else{
			$token =$data['access_token'];
		}
		//echo $this->access_token;exit;
		//$url=http://www.58daiyan.com/user/order_info/order/2017102350495751.html
		//模板消息	
		$template=array(
			'touser'=>$openid,
			'template_id'=>"v_tyYm7HD-zMHW9m7U94PgOAw2nD4sedXLgYv10G_Mo",
			'url'=>$url,
			'topcolor'=>"#7B68EE",
			'data'=>array(
				'first'=>array('value'=>urlencode("您好，您的订单已付款成功"),'color'=>"#000000"),
				'keyword1'=>array('value'=>urlencode($keyword1),'color'=>'#000000'),
				'keyword2'=>array('value'=>urlencode($keyword2),'color'=>'#000000'),
				'keyword3'=>array('value'=>urlencode($keyword3),'color'=>'#000000'),
				'keyword4'=>array('value'=>urlencode($keyword4),'color'=>'#000000'),
				'remark'=>array('value'=>urlencode('祝您购物愉快！'),'color'=>'#000000'),
				)
		);
		$json_template=json_encode($template);
		//echo $json_template;
		//echo $this->access_token;
		$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
		$res=http_request($url,urldecode($json_template));
		if($res){
			if ($res[errcode]==0){
				file_put_contents("tongzhi.txt", date("Y-m-d H:i:s") . "订单".$keyword1."微信通知成功". "\r\n", FILE_APPEND);
			}elseif($res[errcode]==43004){
				file_put_contents("tongzhi.txt", date("Y-m-d H:i:s") . "订单".$keyword1."微信通知,需要关注公众号". "\r\n", FILE_APPEND);
			} 
		}
		
		
	}
	
	/*发货通知
	* @param string $openid：用户OPPENDID
	* @param string $url：订单URL
	* @param string $keyword1：订单编号
	* @param string $keyword2：快递公司
	* @param string $keyword3：快递单号
	*/
	function send_wuliu($openid,$url,$keyword1,$keyword2,$keyword3){
		$appid=C('weixin.APP_KEY');
    	$appsecret=C('weixin.APP_SECRET');
		$data = json_decode(file_get_contents("access_token.json"),true);//建立一个文件把第一次请求到的token对象放进去
		
		if (empty($data) || $data['expire_time']< time()) {
			$json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret);
			$access_token=json_decode($json_token,true);
			//获得access_token
			$token=$access_token[access_token];
			if($token) {
				 $data['expire_time'] = time()+($access_token['expires_in'] - 100);
				 $data['access_token'] = $token;
				 $fp = fopen("access_token.json", "w");
				 fwrite($fp, json_encode($data));
				 fclose($fp);
			}
		}else{
			$token =$data['access_token'];
		}
		
		
		//echo $this->access_token;exit;
		//$url=http://www.58daiyan.com/user/order_info/order/2017102350495751.html
		//模板消息	
		$template=array(
			'touser'=>$openid,
			'template_id'=>"lAqt-yxWjfQjHabp_Hsz90oiHM25WooyPU1JzmQYUCk",
			'url'=>$url,
			'topcolor'=>"#7B68EE",
			'data'=>array(
				'first'=>array('value'=>urlencode("您好，您的订单已发货"),'color'=>"#000000"),
				'keyword1'=>array('value'=>urlencode($keyword1),'color'=>'#000000'),
				'keyword2'=>array('value'=>urlencode($keyword2),'color'=>'#000000'),
				'keyword3'=>array('value'=>urlencode($keyword3),'color'=>'#000000'),
				'remark'=>array('value'=>urlencode('请注意查收！'),'color'=>'#000000'),
				)
		);
		file_put_contents("fahuo.txt", var_export($template,true));
		$json_template=json_encode($template);
		//echo $json_template;
		//echo $this->access_token;
		$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
		$res=http_request($url,urldecode($json_template));
		
		if($res){
			if ($res[errcode]==0){
				file_put_contents("tongzhi.txt", date("Y-m-d H:i:s") . "订单已发货".$keyword3."微信通知成功". "\r\n", FILE_APPEND);
			}elseif($res[errcode]==43004){
				file_put_contents("tongzhi.txt", date("Y-m-d H:i:s") . "订单已发货".$keyword3."微信通知,需要关注公众号". "\r\n", FILE_APPEND);
			} 
		}
		
		
	}

/*订单收货代言通知
	* @param string $openid：用户OPPENDID
	* @param string $url：订单URL
	* @param string $keyword1：购买日期
	* @param string $keyword2：订单号码
	*/
	function send_info_daiyan($openid,$url,$keyword1,$keyword2){
		$appid=C('weixin.APP_KEY');
    	$appsecret=C('weixin.APP_SECRET');
        $data = json_decode(file_get_contents("access_token.json"),true);//建立一个文件把第一次请求到的token对象放进去

		if (empty($data) || $data['expire_time']< time()) {
			$json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret);
			$access_token=json_decode($json_token,true);
			//获得access_token
			$token=$access_token[access_token];
			if($token) {
				 $data['expire_time'] = time()+($access_token['expires_in'] - 100);
				 $data['access_token'] = $token;
				 $fp = fopen("access_token.json", "w");
				 fwrite($fp, json_encode($data));
				 fclose($fp);
			}
		}else{
			$token =$data['access_token'];
		}
		//echo $this->access_token;exit;
		//$url=http://www.58daiyan.com/user/order_info/order/2017102350495751.html
		//模板消息
		$template=array(
			'touser'=>$openid,
			'template_id'=>"CZi0T6Zeku9FxtCYFBrHHuNPIojm5BodhNm5oSlyNuc",
			'url'=>$url,
			'topcolor'=>"#7B68EE",
			'data'=>array(
				'first'=>array('value'=>urlencode("恭喜您获得新的代言资格，请及时查看"),'color'=>"#000000"),
				'keyword1'=>array('value'=>urlencode($keyword1),'color'=>'#000000'),
				'keyword2'=>array('value'=>urlencode($keyword2),'color'=>'#000000'),
			    'remark'=>array('value'=>urlencode('祝您购物愉快！'),'color'=>'#000000'),
				)
		);

		$json_template=json_encode($template);
		//echo $json_template;
		//echo $this->access_token;
		$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
		$res=http_request($url,urldecode($json_template));
        if($res){
			if ($res[errcode]==0){
				file_put_contents("tongzhi.txt", date("Y-m-d H:i:s") . "订单".$keyword1."微信收货通知成功". "\r\n", FILE_APPEND);
			}elseif($res[errcode]==43004){
				file_put_contents("tongzhi.txt", date("Y-m-d H:i:s") . "订单".$keyword1."微信收货通知,需要关注公众号". "\r\n", FILE_APPEND);
			}
		}


	}



/*抵扣券领取通知
	* @param string $openid：用户OPPENDID
	* @param string $url：抵扣券URL
	* @param string $keyword1：购买日期
	* @param string $keyword2：订单号码
	*/
function send_info_dikouquan($openid,$keyword1,$keyword2){
    $appid=C('weixin.APP_KEY');
    $appsecret=C('weixin.APP_SECRET');
    $data = json_decode(file_get_contents("access_token.json"),true);//建立一个文件把第一次请求到的token对象放进去

    if (empty($data) || $data['expire_time']< time()) {
        $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret);
        $access_token=json_decode($json_token,true);
        //获得access_token
        $token=$access_token[access_token];
        if($token) {
            $data['expire_time'] = time()+($access_token['expires_in'] - 100);
            $data['access_token'] = $token;
            $fp = fopen("access_token.json", "w");
            fwrite($fp, json_encode($data));
            fclose($fp);
        }
    }else{
        $token =$data['access_token'];
    }
    //echo $this->access_token;exit;
    //$url=http://www.58daiyan.com/user/order_info/order/2017102350495751.html
    //模板消息
    $template=array(
        'touser'=>$openid,
        'template_id'=>"WrsSa9fjgHJmvzGMmXBbssPkr22UiDf0GnQQTV_4Orc",
        'url'=>'https://m.58daiyan.com/user/bonus.html',
        'topcolor'=>"#7B68EE",
        'data'=>array(
            'first'=>array('value'=>urlencode("恭喜您获得一张抵扣券，请及时查看"),'color'=>"#000000"),
            'keyword1'=>array('value'=>urlencode($keyword1),'color'=>'#000000'),
            'keyword2'=>array('value'=>urlencode($keyword2),'color'=>'#000000'),
            'remark'=>array('value'=>urlencode('感谢您的关注，抵扣券已发放至您账户，逾期抵扣券将失效。祝您购物愉快！'),'color'=>'#000000'),
        )
    );

    $json_template=json_encode($template);
    //echo $json_template;
    //echo $this->access_token;
    $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
    $res=http_request($url,urldecode($json_template));
    if($res){
        if ($res[errcode]==0){
            file_put_contents("tongzhi.txt", date("Y-m-d H:i:s") . "订单".$keyword1."微信通知成功". "\r\n", FILE_APPEND);
        }elseif($res[errcode]==43004){
            file_put_contents("tongzhi.txt", date("Y-m-d H:i:s") . "订单".$keyword1."微信通知,需要关注公众号". "\r\n", FILE_APPEND);
        }
    }


}

/*获得红包通知
	* @param string $openid：用户OPPENDID
	* @param string $url：抵扣券URL
	* @param string $keyword1：购买日期
	* @param string $keyword2：订单号码
	*/
function send_info_hongbao($openid,$url,$keyword1,$keyword2){
    $appid=C('weixin.APP_KEY');
    $appsecret=C('weixin.APP_SECRET');
    $data = json_decode(file_get_contents("access_token.json"),true);//建立一个文件把第一次请求到的token对象放进去

    if (empty($data) || $data['expire_time']< time()) {
        $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret);
        $access_token=json_decode($json_token,true);
        //获得access_token
        $token=$access_token[access_token];
        if($token) {
            $data['expire_time'] = time()+($access_token['expires_in'] - 100);
            $data['access_token'] = $token;
            $fp = fopen("access_token.json", "w");
            fwrite($fp, json_encode($data));
            fclose($fp);
        }
    }else{
        $token =$data['access_token'];
    }
    //echo $this->access_token;exit;
    //$url=http://www.58daiyan.com/user/order_info/order/2017102350495751.html
    //模板消息
    $template=array(
        'touser'=>$openid,
        'template_id'=>"WrsSa9fjgHJmvzGMmXBbssPkr22UiDf0GnQQTV_4Orc",
        'url'=>$url,
        'topcolor'=>"#7B68EE",
        'data'=>array(
            'first'=>array('value'=>urlencode("恭喜您新的代言奖励，请及时查看"),'color'=>"#000000"),
            'keyword1'=>array('value'=>urlencode($keyword1),'color'=>'#000000'),
            'keyword2'=>array('value'=>urlencode($keyword2),'color'=>'#000000'),
            'remark'=>array('value'=>urlencode('感谢您的关注，代言奖励会根据推荐者的订单状态随时更新。祝您购物愉快！'),'color'=>'#000000'),
        )
    );

    $json_template=json_encode($template);
    //echo $json_template;
    //echo $this->access_token;
    $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
    $res=http_request($url,urldecode($json_template));
    if($res){
        if ($res[errcode]==0){
            file_put_contents("tongzhi.txt", date("Y-m-d H:i:s") . "订单".$keyword1."微信通知成功". "\r\n", FILE_APPEND);
        }elseif($res[errcode]==43004){
            file_put_contents("tongzhi.txt", date("Y-m-d H:i:s") . "订单".$keyword1."微信通知,需要关注公众号". "\r\n", FILE_APPEND);
        }
    }


}
	//判断是否关注
	function is_fllow($openid){
		$appid=C('weixin.APP_KEY');
    	$appsecret=C('weixin.APP_SECRET');
		
		$data = json_decode(file_get_contents("access_token.json"),true);//建立一个文件把第一次请求到的token对象放进去
		
		if (empty($data) || $data['expire_time']< time()) {
			$json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret);
			$access_token=json_decode($json_token,true);
			//获得access_token
			$token=$access_token[access_token];
			if($token) {
				 $data['expire_time'] = time()+($access_token['expires_in'] - 100);
				 $data['access_token'] = $token;
				 $fp = fopen("access_token.json", "w");
				 fwrite($fp, json_encode($data));
				 fclose($fp);
			}
		}else{
			$token =$data['access_token'];
		}
		$access_token = $token;
		$info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
		$userinfo = json_decode(get_url_contents($info_url),true);
		return $userinfo;
	}
	/**
	 * 获取当前页面完整URL地址
	 */
	function get_url() {
	    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
	    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
	    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
	    return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
	}
	
	function get_wuliu_info($key){
		$wuliu=M('express')->where('express_no="'.$key.'"')->find();
		return $wuliu['company_name'];
	}
	/**
	 * 合并用户
	 * $uid 目标账号
	 * $buid 被绑定账号
	 */
	function merge_user($uid,$buid){
		$u_user=M('users')->find($uid);
		$b_user=M('users')->find($buid);
		//密码
		if($u_user['password']=='8888888'&&$b_user['password']!='8888888'){
			$newdata['password']=$b_user['password'];
		}
		//手机
		if($u_user['phone']==null&&$b_user['phone']!=null){
			$newdata['phone']=$b_user['phone'];
		}
		//微信
		if($u_user['wx_openid']==null&&$b_user['wx_openid']!=null){
			$newdata['wx_openid']=$b_user['wx_openid'];
		}
		//微博
		if($u_user['wb_openid']==null&&$b_user['wb_openid']!=null){
			$newdata['wb_openid']=$b_user['wb_openid'];
		}
		//QQ
		if($u_user['qq_openid']==null&&$b_user['qq_openid']!=null){
			$newdata['qq_openid']=$b_user['qq_openid'];
		}
		$newdata['id']=$uid;
		$rs=M('users')->save($newdata);
		if($rs){
			M('users')->delete($buid);
			return true;
		}else{
			return false;
		}
		
	}
    function yc_phone($str){
        $str=$str;
        if(preg_match("/^1[34578]{1}\d{9}$/",$str)){
             $resstr=substr_replace($str,'****',3,4);
        }else{
             $resstr=$str;
        }

        return $resstr;
    }

    function shop_type($id){
      $shop=M('shop')->find($id);
      //故事
        $shop_content=M('shop_content')->where('shop_id='.$id)->find();
        if($shop_content['story_title']){
            $rs['story']=$shop_content['story_title'];
        }

      $time=time();
      //团
      if($shop['tuanselect']==1&&$shop['tuanz_starttime']<$time&&$shop['tuanz_endtime']>$time){
         $rs['tuan']=1;
      }else{
         $rs['tuan']=0;
      }
      //优惠券
      $rs['coupon']=0;
      $coupon=M('coupon_goods')->where('goods_id='.$id)->select();
      if($coupon){

          foreach($coupon as $key=>$value){
              $coupon_info=M('coupon_type')->where('coupon_type_id='.$value['coupon_type_id'])->find();
              $start_time=strtotime($coupon_info['start_time']);
              $end_time=strtotime($coupon_info['end_time']);
              if($time>$start_time&&$time<$end_time){
                  $rs['coupon']=1;
              }
          }
      }
      return $rs;
    }

    function get_daiyan_status($shop_id,$uid){
        $flag=false;
        $rs=M('order')
            ->join('yt_order_goods ON yt_order.order_id = yt_order_goods.order_id','left')
            ->where("yt_order_goods.goods_id=$shop_id and (yt_order.order_state='40' or (yt_order.order_state='20' and yt_order.order_type='2')) and yt_order.refund_state='0' and yt_order.buyer_id=$uid ")
            ->find();
        if ($rs){
            $flag=true;
        }else{
            $shop=M('shop')->find($shop_id);
            $store_id=$shop['store_id'];
            $type_id=$shop['type_id'];
            $shop_id=$shop['id'];
            //商品代言
            $rs1=  M('angel')->where("type=1 and type_id=$shop_id and uid=$uid")->find();
            //店铺代言
            $rs2=   M('angel')->where("type=2 and type_id=$store_id and uid=$uid")->find();
            //分类代言
            $rs3=   M('angel')->where("type=3 and type_id  IN ('".$type_id."') and uid=$uid")->find();
            if($rs1!=null || $rs2!=null ||$rs3!=null){
                $flag=true;
            }
        }
		 //判断区域代言
        if($flag==false){
            $area_angel=M('area_angel');
            $rs=$area_angel->where('uid='.$uid.' and status=4')->select();
            $shop=M('shop')->find($shop_id);
            $store_id=$shop['store_id'];
            $store_info=M('store')->find($store_id);
            if($rs){
                foreach ($rs as $key=>$value){
                    if($value['area_type']==1&&$value['district_id']==$store_info['district']){
                        $flag=true;
                    }
                    if($value['area_type']==2&&$value['city_id']==$store_info['city']){
                        $flag=true;
                    }
                    if($value['area_type']==3&&$value['province_id']==$store_info['province']){
                        $flag=true;
                    }
                }
            }
        }
        return $flag;
    }

/**
 * 取汉字的第一个字的首字母
 * @param type $str
 * @return string|null
 */
function _getFirstCharter($str){
    if(empty($str)){return '';}
    $fchar=ord($str{0});
    if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
    $s1=iconv('UTF-8','gb2312',$str);
    $s2=iconv('gb2312','UTF-8',$s1);
    $s=$s2==$str?$s1:$str;
    $asc=ord($s{0})*256+ord($s{1})-65536;
    if($asc>=-20319&&$asc<=-20284) return 'A';
    if($asc>=-20283&&$asc<=-19776) return 'B';
    if($asc>=-19775&&$asc<=-19219) return 'C';
    if($asc>=-19218&&$asc<=-18711) return 'D';
    if($asc>=-18710&&$asc<=-18527) return 'E';
    if($asc>=-18526&&$asc<=-18240) return 'F';
    if($asc>=-18239 && $asc <= -17760) return "G";
    if($asc>=-17759 && $asc <= -17248) return "H";
    if($asc>=-17247 && $asc <= -17418) return "I";


    if($asc>=-17417&&$asc<=-16475) return 'J';
    if($asc>=-16474&&$asc<=-16213) return 'K';
    if($asc>=-16212&&$asc<=-15641) return 'L';
    if($asc>=-15640&&$asc<=-15166) return 'M';
    if($asc>=-15165&&$asc<=-14923) return 'N';
    if($asc>=-14922&&$asc<=-14915) return 'O';
    if($asc>=-14914&&$asc<=-14631) return 'P';
    if($asc>=-14630&&$asc<=-14150) return 'Q';
    if($asc>=-14149&&$asc<=-14091) return 'R';
    if($asc>=-14090&&$asc<=-13319) return 'S';
    if($asc>=-13318&&$asc<=-12839) return 'T';
    if($asc>=-12838&&$asc<=-12557) return 'W';
    if($asc>=-12556&&$asc<=-11848) return 'X';
    if($asc>=-11847&&$asc<=-11056) return 'Y';
    if($asc>=-11055&&$asc<=-10247) return 'Z';
    return null;
}

function geCharter($str){
    if(empty($str)){return '';}
    $fchar=ord($str{0});
    if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
    $s1=iconv('UTF-8','gb2312',$str);
    $s2=iconv('gb2312','UTF-8',$s1);
    $s=$s2==$str?$s1:$str;
    $asc=ord($s{0})*256+ord($s{1})-65536;
   echo $asc;
}


/**************************************************************
 *
 *	使用特定function对数组中所有元素做处理
 *	@param	string	&$array		要处理的字符串
 *	@param	string	$function	要执行的函数
 *	@return boolean	$apply_to_keys_also		是否也应用到key上
 *	@access public
 *
 *************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
    static $recursive_counter = 0;
    if (++$recursive_counter > 1000) {
        die('possible deep recursion attack');
    }
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            arrayRecursive($array[$key], $function, $apply_to_keys_also);
        } else {
            $array[$key] = $function($value);
        }

        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
    $recursive_counter--;
}


function getTree($data, $pId)
{
    $tree = '';
    foreach($data as $k => $v)
    {
        if($v['bclassid'] == $pId)
        {        //父亲找到儿子
            $v['child'] = getTree($data, $v['id']);
            $tree[] = $v;
            //unset($data[$k]);
        }
    }
    return $tree;
}

function getCard($int, $format=8) {
    $dics = array(
        0=>'0',    1=>'1',    2=>'2',    3=>'3',    4=>'4',    5=>'5',    6=>'6',    7=>'7',    8=>'8',    9=>'9',
        10=>'A',    11=>'B',    12=>'C',    13=>'D',    14=>'E',    15=>'F',    16=>'G',    17=>'H',    18=>'I',
        19=>'J',    20=>'K',    21=>'L',    22=>'M',    23=>'N',    24=>'O',    25=>'P',    26=>'Q',    27=>'R',
        28=>'S',    29=>'T',    30=>'U',    31=>'V',    32=>'W',    33=>'X',    34=>'Y',    35=>'Z'
    );
    $dnum = 36; //进制数
    $arr = array ();
    $loop = true;
    while ($loop) {
        $arr[] = $dics[bcmod($int, $dnum)];
        $int = bcdiv($int, $dnum, 0);
        //echo $int.'<br/>';
        if ($int == '0') {
            $loop = false;
        }
    }
    if (count($arr) < $format)
        $arr = array_pad($arr, $format, $dics[0]);
    return implode('', array_reverse($arr));
}

?>